package com.barray.log_monitor;

import android.content.Context;
import android.os.Environment;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class LogcatHelper {
    private static LogcatHelper INSTANCE = null;
    private static String PATH_LOGCAT;
    private LogDumper mLogDumper = null;
    private final int mPId;

    public List<LogBean> getLogList(){
        List<LogBean> logBeans = new ArrayList<>();
        File file = new File(PATH_LOGCAT);
        if (file.exists() && file.isDirectory()) {
            File[] files = file.listFiles();
            if(files != null){
                for(File f :files){
                    if(f.isFile() && f.getName().endsWith(".log")){
                        LogBean logBean = new LogBean();
                        logBean.setFileName(f.getName());
                        logBean.setFilePath(f.getAbsolutePath());
                        logBean.setFileSize(fixSize(f.length()));
                        logBeans.add(logBean);
                    }
                }
            }
        }
        return logBeans;
    }

    public void clear(){
        File file = new File(PATH_LOGCAT);
        if (file.exists() && file.isDirectory()) {
            File[] files = file.listFiles();
            if(files != null){
                for(File f :files){
                    f.delete();
                }
            }
        }
    }

    private String fixSize(long size){
        if(size < 1000){
            return fixSizeString(String.valueOf(size),"B");
        }
        double result = size/1000.0;
        if(result < 1000){
            return fixSizeString(String.valueOf(result),"KB");
        }else{
            result = size/1000.0;
            if(result < 1000){
                return fixSizeString(String.valueOf(result),"MB");
            }else {
                result = size/1000.0;
                return fixSizeString(String.valueOf(result),"GB");
            }
        }
    }

    private String fixSizeString(String size,String unit){
        if(size == null) return null;
        int index = size.indexOf(".");
        if(index == -1) return size + unit;
        if(index + 3 >= size.length()){
            return size + unit;
        }else{
            return size.substring(0,index+4) + unit;
        }
    }



    /**
     * 初始化目录
     * @param context
     */
    public void init(Context context) {
        if (Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED)) {// 优先保存到SD卡中
            PATH_LOGCAT = context.getExternalFilesDir(null).getAbsolutePath()
                    + File.separator + "log";
        } else {// 如果SD卡不存在，就保存到本应用的目录下
            PATH_LOGCAT = context.getFilesDir().getAbsolutePath()
                    + File.separator + "log";
        }
        File file = new File(PATH_LOGCAT);
        if (!file.exists()) {
            file.mkdirs();
        }
    }

    public static LogcatHelper getInstance(Context context) {
        if (INSTANCE == null) {
            INSTANCE = new LogcatHelper(context);
        }
        return INSTANCE;
    }

    private LogcatHelper(Context context) {
        init(context);
        mPId = android.os.Process.myPid();
    }

    public void start() {
        if (mLogDumper == null || !mLogDumper.mRunning || mLogDumper.getState() != Thread.State.TERMINATED){
            mLogDumper = new LogDumper(String.valueOf(mPId), PATH_LOGCAT);
            mLogDumper.start();
        }
    }

    public void hello(){
        try{

        }catch (NullPointerException ne){

        }catch (IndexOutOfBoundsException ie){

        }
    }

    public void stop() {
        if (mLogDumper != null) {
            mLogDumper.stopLogs();
            mLogDumper = null;
        }
    }

    private class LogDumper extends Thread {
        private Process logcatProc;
        private BufferedReader mReader = null;
        private boolean mRunning = true;
        String cmdContent;
        private String mPID;
        private FileOutputStream out = null;

        public LogDumper(String pid, String dir) {
            mPID = pid;
            try {
                out = new FileOutputStream(new File(dir, getFileName() + ".log"));
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }

            // 日志等级：*:v , *:d , *:w , *:e , *:f , *:s
            // 显示当前mPID程序的 E和W等级的日志.

            // cmds = "logcat *:e *:w | grep \"(" + mPID + ")\"";
            // cmds = "logcat  | grep \"(" + mPID + ")\"";//打印所有日志信息
            // cmds = "logcat -s way";//打印标签过滤信息
            cmdContent = "logcat *:e *:i | grep \"(" + mPID + ")\"";

        }

        public void stopLogs() {
            mRunning = false;
        }

        @Override
        public void run() {
            while (mRunning){
                printLog();
            }
        }


        private void printLog(){
            try {
                logcatProc = Runtime.getRuntime().exec(cmdContent);
                mReader = new BufferedReader(new InputStreamReader(
                        logcatProc.getInputStream()), 1024);
                String line = null;
                while (mRunning && (line = mReader.readLine()) != null) {
                    if (!mRunning) {
                        break;
                    }
                    if (line.length() == 0) {
                        continue;
                    }
                    if (out != null && line.contains(mPID)) {
                        out.write((line + "\n").getBytes());
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (logcatProc != null) {
                    logcatProc.destroy();
                    logcatProc = null;
                }
                if (mReader != null) {
                    try {
                        mReader.close();
                        mReader = null;
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (out != null) {
                    try {
                        out.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    out = null;
                }
            }
        }

    }
    public  String getFileName() {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss");
        return format.format(new Date(System.currentTimeMillis()));
    }
}
